# -*- coding: utf-8 -*-
from SiteJD import *
from SiteAmazon import *
from SiteDangdang import *
from SiteAlibaba import *
from SiteTmall import *
from SiteTaobao import *
from CC import *
from DB import *
import threading
import uuid
import sys

class Task:

    def __init__(self, userid):
        self.userid = userid
        self.cc = CC(userid)

    def fetchSite(self, site, keyword):
        site.getAll(keyword)

    def run(self):
        #print '-- task started'

        sites = []
        if self.cc.SiteJD:
            sites.append(SiteJD(self.cc))

        if self.cc.SiteAmazon:
            sites.append(SiteAmazon(self.cc))

        if self.cc.SiteDangdang:
            sites.append(SiteDangdang(self.cc))

        if self.cc.SiteAlibaba:
            sites.append(SiteAlibaba(self.cc))

        if self.cc.SiteTmall:
            sites.append(SiteTmall(self.cc))

        if self.cc.SiteTaobao:
            sites.append(SiteTaobao(self.cc))


        thr_list = []

        for site in sites:
            if self.cc.isQuitted():
                break

            t = threading.Thread(target = self.fetchSite, args = (site, self.cc.Keyword))
            thr_list.append(t)
            t.start()

        for t in thr_list:
            t.join()

        self.cc.stop()

        #print '-- task stopped'

    def start(self, keyword, price):
        #print '-- task.isStoped', self.cc.isStopped()

        if self.cc.isStopped():
            self.cc.start(keyword, price)
            task_id = self.cc.getTaskId()
            et = threading.Thread(target = self.run)
            et.setDaemon(True)
            et.start()
            return task_id

        return ''

    def stop(self):
        self.cc.quit()
        return True

    def isStoped(self):
        return self.cc.isStopped()

    def getCC(self):
        return self.cc

    def clear(self):
        db = DB()
        db.Execute('DELETE FROM TaskProducts WHERE UserId = %s', (self.userid,))
        db.Commit()
        db.Close()

    def data(self, offset, limit):
        if self.cc.Keyword == '':
            return []

        db = DB()
        o = db.FetchAll('SELECT Platform, Description, Link, Price, LeftCount, SellCount, ShopName, ShopLink, ShopLevel FROM TaskProducts WHERE UserId = %s LIMIT %s, %s', (self.userid, offset, limit))
        db.Close()

        standard_price = self.cc.Price
        items = []
        for v in o:
            item = {}
            item['platform'] = v[0]
            item['description'] = v[1]
            item['link'] = v[2]

            try:
                item['price'] = '%.2f' % float(v[3])
            except:
                item['price'] = ''

            item['left_count'] = v[4]
            item['sell_count'] = v[5]
            item['shop_name'] = v[6]
            item['shop_link'] = v[7]
            item['shop_level'] = v[8]
            item['standard_price'] = '%.2f' % standard_price

            item['discount'] = ''
            if item['price'] != '':
                try:
                    item['discount'] = '%.2f%%' % (100.0 * float(v[3]) / standard_price)
                except:
                    pass

            items.append(item)

        return items

